package cn.jdy.task.admin;

import cn.jdy.framework.log.BaseLog;
import cn.jdy.task.entity.SchedulingJob;
import cn.jdy.task.service.SchedulerService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/timer")
public class TimerCtrl {

	@Resource
	private SchedulerService schedulerService;

	@RequestMapping("/list")
	public ModelAndView list() {
		ModelAndView mv = new ModelAndView("/platform/timerManager.jsp");
		mv.addObject(schedulerService.jobGroupMap);
		return mv;
	}

	/**
	 * 查询所有订单
	 */
	@RequestMapping("findTimers")
	@ResponseBody
	public Map<String, Object> findTimers(SchedulingJob entity) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			jsonMap.put("dataList", this.schedulerService.queryTimers(entity));
			jsonMap.put("iTotalRecords", schedulerService.count());
			jsonMap.put("iTotalDisplayRecords", schedulerService.count(entity));
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "findTimers", e);
		}
		return jsonMap;
	}

	@RequestMapping("/save")
	@ResponseBody
	public Map<String, Object> save(SchedulingJob schedulingJob) {
		Map<String, Object> rtnMap = new HashMap<String, Object>();
		try {
			schedulerService.saveOrUpd(schedulingJob);
			rtnMap.put("statusCode", 200);
		}catch(Exception e) {
			BaseLog.e(getClass(), "定时任务保存异常！", e);
			rtnMap.put("statusCode", 500);
			rtnMap.put("info", "保存失败！");
		}
		return rtnMap;
	}
	
	@RequestMapping("/delete")
	@ResponseBody
	public Map<String, Object> delete(Long id) {
		Map<String, Object> rtnMap = new HashMap<String, Object>();
		try {
			schedulerService.delete(id);
			rtnMap.put("statusCode", 200);
		}catch(Exception e) {
			BaseLog.e(getClass(), "定时任务删除异常："+id, e);
			rtnMap.put("statusCode", 500);
			rtnMap.put("info", "删除失败！");
		} 
		return rtnMap;
	}
	
	/**
	 * 立即执行一次
	 * @param schedulingJob
	 * @return
	 */
	@RequestMapping("/trigger")
	@ResponseBody
	public Map<String, Object> triggerJob(SchedulingJob schedulingJob) {
		Map<String, Object> rtnMap = new HashMap<String, Object>();
		try {
			schedulerService.triggerJob(schedulingJob);
			rtnMap.put("statusCode", 200);
		} catch (Exception e) {
			BaseLog.e(getClass(), "手动触发定时任务异常："+schedulingJob.getId(), e);
			rtnMap.put("statusCode", 500);
			rtnMap.put("info", "操作失败！");
		}
		return rtnMap;
	}
}
